/**
 * Definition for singly-linked list.*/
export class ListNode {
    val: number
    next: ListNode | null
    constructor(val?: number, next?: ListNode | null) {
        this.val = (val===undefined ? 0 : val)
        this.next = (next===undefined ? null : next)
    }
}

// class ListNodeUse {
//     // ts function 不能放class里？？？报错
// }

// 字符串转一维整型数组
export function stringToIntegerArray(input: string): number[] {
    input = input.trim();
    input = input.substring(1, input.length-1);
    if (input.length == 0) {
        return [];
    }

    const parts: string[] = input.split(",");
    const output: number[] = new Array(parts.length).fill(0);
    for (let index=0; index<parts.length; ++index) {
        let part: string = parts[index].trim();
        output[index] = parseInt(part);
    }
    return output;
}

// 字符串转链表
export function stringToListNode(input: string): ListNode | null {
    const nodeValues: number[] = stringToIntegerArray(input);
    // 这样像new Array可以吧？
    let dummyRoot: ListNode | null = new ListNode(0);
    let ptr: ListNode | null = dummyRoot;
    // let item:nodeValues 遍历报错，ts不支持？！！
    for (let i=0; i<nodeValues.length; ++i) {
        let item: number = nodeValues[i];
        // 这样像new Array可以吧？
        ptr.next = new ListNode(item);
        ptr = ptr.next;
    }
    return dummyRoot.next;
}

// 链表转字符串
export function listNodeToString(node: ListNode | null): string {
    if (node === null) {
        return "[]";
    }
    let result: string = "";
    while (node != null) {
        // ", " 空格必须的，要不要改下面的substring 0~2
        result += node.val + ", ";
        node = node.next;
    }
    console.log("result: ", result);

    return "[" + result.substring(0, result.length - 2) + "]";
}

export function prettyPrintLinkedList(node: ListNode | null) {
    let ans: string = "";
    while (node != null && node.next != null) {
        // 不能用换行
        // console.log(node.val + "->");
        ans += node.val + "->";
        node = node.next;
    }

    if (node != null) {
        // console.log(node.val);
        ans += node.val;
    } else {
        console.log("Empty LinkedList!");
    }
    console.log("ans: ", ans);
}